import React, { useContext, useEffect, useImperativeHandle, useMemo, useState } from 'react';
import UpdatePackList from './UpdatePackList';
import { ApplyUpdateContext } from '../common/ApplyContext';
import { DictionaryService } from '../services/DictionaryService';
import { formatDecimal, renderFileFunc } from '../../Acommon';
import { DescriptionsType, useDescriptionsType } from '@/components/DescriptionsType';
import { Drawer, Table, Tooltip, message } from 'antd';
import { getColorTextLoadMap, getCompanyID, getKeyRouter } from '@/utils';
import { handleOneObjectData, KYFW_Type, KYWZ_Type, PURCHASE_Type, setTableRowClassName, ZNGL_Type } from '../common/Format';
import { getPackTableColumns } from '../mconfig';
import { EyeOutlined, EyeInvisibleOutlined } from '@ant-design/icons';
import '../common/style.less';
import { history } from 'umi';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import { findValueFun } from '@/common';
/**
 * @UpdateStepsApply 步骤条第三步申请信息
 */
const UpdateStepsApply = React.forwardRef(({}: Record<string, any>, ref) => {
  /**上下文*/
  const { applyInfo, curRes } = useContext(ApplyUpdateContext);
  /**采购办法*/
  const { supplyWayList } = DictionaryService();
  /**标包数据*/
  const [packList, setPackList] = useState<Record<string, any>[]>([]);
  /**抽屉的显示*/
  const [open, setOpen] = useState<Record<string, any>>({});
  /** 是否显示对应的表格 */
  const [isShowObj, setIsShowObj] = useState<Record<string, any>>({
    isShowUpload: 0, // 标的来源
    isShowOther: 0, // 其他
    isShowCommon: 0, // 是否共性
    isShowPlatform: 0, // 是否平台
    isShowCategory: 0, // 采购类别
    isShowConsign: 0, // 是否会签
    isShowMeeting: 0, // 是否上会
  });
  /**信息确认-表格配置*/
  const [config, { setFieldsValue, validateFields }] = useDescriptionsType({
    labelWidth: 240,
    isShowNumTitle: false,
    schemas: [
      {
        key: 'applyInfoDesType',
        title: '信息确认',
        fieldChildren: [
          {
            label: '申请日期',
            field: 'applyTime',
            component: 'Input',
            placeholder: '自动带出',
            disabled: true,
          },
          {
            label: '流水单号',
            field: 'applyCode',
            component: 'Input',
            disabled: true,
            placeholder: '自动带出',
          },
          {
            label: '申请人',
            field: 'applyerName',
            component: 'Input',
            disabled: true,
            placeholder: '自动带出',
          },
          {
            label: '联系方式',
            field: 'contactMobile',
            component: 'Input',
            disabled: true,
            placeholder: '自动带出',
          },
          {
            label: '申请部门/单位',
            field: 'applyDepartmentName',
            component: 'Input',
            disabled: true,
            placeholder: '自动带出',
          },
          {
            label: '职务岗位',
            field: 'applyPositionName',
            component: 'Input',
            placeholder: '自动带出',
            disabled: true,
          },
          {
            label: '采购项目名称',
            field: 'applyTitle',
            component: 'Input',
            disabled: true,
            placeholder: '自动带出',
            colSpan: 2,
          },
          {
            label: '采购类别',
            field: 'purchCategory',
            component: 'Render',
            disabled: true,
            colSpan: 1,
            render: (text = 0, record) => {
              return <span>{findValueFun(PURCHASE_Type, text)}</span>;
            },
          },
          {
            label: '采购内容',
            field: 'purchContent',
            component: 'Render',
            disabled: true,
            colSpan: 1,
            render: (text = 0, record) => {
              return (
                <span>
                  {record?.purchCategory == 0
                    ? findValueFun(KYWZ_Type, text)
                    : record?.purchCategory == 1
                    ? findValueFun(KYFW_Type, text)
                    : record?.purchCategory == 2
                    ? findValueFun(ZNGL_Type, text)
                    : '--'}
                </span>
              );
            },
          },
          {
            label: '其他内容',
            field: 'otherContent',
            component: 'InputTextArea',
            disabled: true,
            colSpan: 2,
            ishidden: isShowObj?.isShowOther == 3 ? false : true,
            placeholder: '--',
            // required: true,
            showCount: true,
            allowClear: true,
            maxLength: 200,
            autoSize: { minRows: 4, maxRows: 6 },
          },
          {
            label: '是否共性',
            field: 'commonFlag',
            component: 'Render',
            colSpan: isShowObj?.isShowCommon == 0 ? 2 : 1,
            ishidden: isShowObj?.isShowCategory == 1 || isShowObj?.isShowCategory == 2 ? true : false,
            slotRender: (text: any = 0) => {
              return <span style={{ marginLeft: '8px' }}>{text == 0 ? '否' : text == 1 ? '是' : '--'}</span>;
            },
          },
          {
            label: '实验室业务归口部门',
            field: 'commonDepartmentName',
            component: 'Input',
            placeholder: '--',
            colSpan: isShowObj?.isShowCommon == 0 ? 2 : 1,
            ishidden: isShowObj?.isShowCommon == 0 ? true : isShowObj?.isShowCategory == 1 || isShowObj?.isShowCategory == 2 ? true : false,
            // required: true,
            disabled: true,
          },
          {
            label: '是否平台',
            field: 'platformFlag',
            component: 'Render',
            colSpan: isShowObj?.isShowPlatform == 0 ? 2 : 1,
            slotRender: (text: any = 0) => {
              return <span style={{ marginLeft: '8px' }}>{text == 0 ? '否' : text == 1 ? '是' : '--'}</span>;
            },
          },
          {
            label: '平台归口部门',
            field: 'platformDepartmentName',
            component: 'Input',
            placeholder: '--',
            colSpan: isShowObj?.isShowPlatform == 0 ? 2 : 1,
            ishidden: isShowObj?.isShowPlatform == 0 ? true : false,
            // required: true,
            disabled: true,
          },
          {
            label: '是否会签',
            field: 'consignFlag',
            component: 'Render',
            colSpan: isShowObj?.isShowConsign == 0 ? 2 : 1,
            ishidden: isShowObj?.isShowCategory == 0 || isShowObj?.isShowCategory == 1 ? true : false,
            slotRender: (text: any = 0) => {
              return <span style={{ marginLeft: '8px' }}>{text == 0 ? '否' : text == 1 ? '是' : '--'}</span>;
            },
          },
          {
            label: '实验室会签部门',
            field: 'consignDepartmentName',
            component: 'Input',
            placeholder: '--',
            colSpan: isShowObj?.isShowConsign == 0 ? 2 : 1,
            ishidden: isShowObj?.isShowConsign == 0 ? true : isShowObj?.isShowCategory == 0 || isShowObj?.isShowCategory == 1 ? true : false,
            disabled: true,
          },
          {
            label: '是否上会',
            field: 'meetingFlag',
            component: 'Render',
            colSpan: isShowObj?.isShowMeeting == 0 ? 2 : 1,
            ishidden: isShowObj?.isShowCategory == 0 || isShowObj?.isShowCategory == 1 ? true : false,
            slotRender: (text: any = 0) => {
              return <span style={{ marginLeft: '8px' }}>{text == 0 ? '否' : text == 1 ? '是' : '--'}</span>;
            },
          },
          {
            label: '会议纪要',
            field: 'meetingSummaryUrl',
            placeholder: '请上传会议纪要',
            component: 'Render',
            colSpan: isShowObj?.isShowMeeting == 0 ? 2 : 1,
            ishidden: isShowObj?.isShowMeeting == 0 ? true : isShowObj?.isShowCategory == 0 || isShowObj?.isShowCategory == 1 ? true : false,
            slotRender: (text, record) => {
              return (
                <span style={{ marginLeft: 8 }}>
                  {renderFileFunc({
                    record: applyInfo,
                    fileName: 'meetingSummaryUrl',
                    downloadAddress: '/purchaseApplyController/downloadFile',
                    returnStr: '/',
                  })}
                </span>
              );
            },
          },
          {
            label: '标的来源',
            field: 'supplyWay',
            component: 'Input',
            disabled: true,
            placeholder: '自动带出',
            // colSpan: isShowObj?.isShowUpload == 1 ? 1 : 2,
            colSpan: 2,
            render: (text) => {
              let word: any = <span style={{ color: '#bfc0c1' }}>自动带出</span>;
              if (typeof text != 'undefined') {
                word =
                  supplyWayList?.filter((item) => {
                    return item?.value == (text as any);
                  })?.[0]?.name ?? word;
              }
              return <span>{word}</span>;
            },
          },
          // {
          //   field: `unitDepartmentID`,
          //   label: '业务归口部门',
          //   component: 'Render',
          //   disabled: true,
          //   placeholder: '--',
          //   colSpan: isShowObj?.isShowUpload == 1 && getCompanyID() != '1' ? 1 : 0,
          //   ishidden: isShowObj?.isShowUpload == 1 && getCompanyID() != '1' ? false : true,
          //   render: () => {
          //     return <span>{applyInfo?.unitDepartmentName || ''}</span>;
          //   },
          // },
          // {
          //   field: `busiDepartmentID`,
          //   label: getCompanyID() == '1' && isShowObj?.isShowUpload == 1 ? '本单位业务归口部门' : `实验室业务归口部门`,
          //   component: 'Render',
          //   disabled: true,
          //   placeholder: '--',
          //   colSpan: getCompanyID() == '1' && isShowObj?.isShowUpload == 1 ? 1 : 0,
          //   ishidden: getCompanyID() == '1' && isShowObj?.isShowUpload == 1 ? false : true,
          //   render: () => {
          //     return <span>{applyInfo?.busiDepartmentName || ''}</span>;
          //   },
          // },
          {
            label: '预算金额',
            field: 'expectSum',
            component: 'Input',
            placeholder: '自动带出',
            disabled: true,
            colSpan: 2,
            contentAfter: '元',
          },
          {
            label: '采购理由',
            field: 'applyInfo',
            component: 'InputTextArea',
            placeholder: '自动带出',
            disabled: true,
            showCount: true,
            allowClear: true,
            maxLength: 200,
            autoSize: { minRows: 4, maxRows: 6 },
            colSpan: 2,
          },
        ],
      },
    ],
  });

  /** 表格表单配置 */
  const [configs, methods] = useDescriptionsType({
    labelWidth: 210,
    schemas: [
      {
        key: 'applyInfoDes',
        title: '基本信息',
        isNoShowNum: true,
        fieldChildren: [
          {
            label: '标包名称',
            field: 'packName',
            component: 'Render',
            slotRender: (text: string) => {
              return <span style={{ marginLeft: '8px' }}>{text || '--'}</span>;
            },
          },
          {
            label: '包号',
            field: 'packCode',
            component: 'Input',
            placeholder: '自动带出',
            disabled: true,
          },
          // {
          //   label: '采购类别',
          //   field: 'supplyTypeName',
          //   component: 'Render',
          //   slotRender: (text: string) => {
          //     const { colorText, color } = getColorTextLoadMap(text);
          //     if (colorText) {
          //       return <div style={{ color, paddingLeft: '8px' }}>{colorText || '--'}</div>;
          //     } else {
          //       return <div style={{ color: '#c4c4c3', paddingLeft: '8px' }}>自动带出</div>;
          //     }
          //   },
          // },
          {
            label: '预算金额',
            field: 'expectSum',
            placeholder: '自动带出',
            component: 'Render',
            disabled: true,
            contentAfter: '元',
            slotRender: (text) => {
              return <div style={{ paddingLeft: '8px' }}>{formatDecimal(text)}</div>;
            },
          },
          {
            label: '标的来源',
            field: 'supplyWay',
            placeholder: '自动带出',
            component: 'Select',
            colSpan: 1,
            options: supplyWayList,
            disabled: true,
            fieldNames: {
              label: 'name',
              value: 'value',
            },
          },
          {
            label: '采购组织类型',
            field: 'procureOrgName',
            component: 'Render',
            placeholder: '自动带出',
            disabled: false,
            slotRender: (text: string) => {
              const { colorText, color } = getColorTextLoadMap(text);
              if (colorText) {
                return <div style={{ color, paddingLeft: '8px' }}>{colorText || '--'}</div>;
              } else {
                return <div style={{ color: '#c4c4c3', paddingLeft: '8px' }}>自动带出</div>;
              }
            },
          },
          {
            label: '拟定采购方式',
            placeholder: '自动带出',
            field: 'procureRealName',
            component: 'Render',
            slotRender: (text: string) => {
              const { colorText, color } = getColorTextLoadMap(text);
              if (colorText) {
                return <div style={{ color, paddingLeft: '8px' }}>{colorText || '--'}</div>;
              } else {
                return <div style={{ color: '#c4c4c3', paddingLeft: '8px' }}>自动带出</div>;
              }
            },
          },

          {
            label: '采购方式变更申请单',
            field: 'changeID',
            component: 'Render',
            colSpan: 2,
            slotRender: (text) => {
              return (
                <div style={{ paddingLeft: '8px' }}>
                  {text ? (
                    <Tooltip title={'查看采购方式变更申请单'}>
                      <a>
                        <EyeOutlined
                          onClick={() => {
                            if (curRes?.['/purchaseSourceChangeController/getSourceChangeById/{id}/{currentUserID}']) {
                              history.push({
                                pathname: `/purchaseSourceChangeController/getSourceChangeById/{id}/{currentUserID}/:${getKeyRouter()}${getKeyRouter()}`,
                                state: {
                                  info: { changeID: text },
                                  type: 'view',
                                },
                              });
                            } else {
                              message?.error('抱歉，暂无查看权限！');
                            }
                          }}
                        />
                      </a>
                    </Tooltip>
                  ) : (
                    <Tooltip title="暂无采购方式变更申请单">
                      <a>
                        <EyeInvisibleOutlined />
                      </a>
                    </Tooltip>
                  )}
                </div>
              );
            },
          },
          {
            label: '意向公开名称',
            field: 'intentName',
            component: 'Input',
            placeholder: '--',
            disabled: true,
          },
          {
            label: '意向公开时间',
            field: 'intentTime',
            component: 'Input',
            placeholder: '--',
            disabled: true,
          },
          {
            label: '技术规范',
            field: 'skillNormURL',
            placeholder: '请上传技术规范',
            component: 'Render',
            colSpan: open?.record?.supplyWay && open?.record?.supplyWay == 1 ? 1 : 0,
            // required: true,
            slotRender: () => {
              return (
                <span style={{ marginLeft: 8 }}>
                  {renderFileFunc({
                    record: open?.record || {},
                    fileName: 'skillNormURL',
                    downloadAddress: '/purchaseApplyController/downloadFile',
                    returnStr: '/',
                  })}
                </span>
              );
            },
          },
          {
            label: '调研报告',
            field: 'researchReportURL',
            placeholder: '请上传调研报告',
            component: 'Render',
            colSpan: open?.record?.supplyWay && open?.record?.supplyWay == 1 ? 1 : 0,
            // required: true,
            slotRender: () => {
              return (
                <span style={{ marginLeft: 8 }}>
                  {renderFileFunc({
                    record: open?.record || {},
                    fileName: 'researchReportURL',
                    downloadAddress: '/purchaseApplyController/downloadFile',
                    returnStr: '/',
                  })}
                </span>
              );
            },
          },
          {
            label: '是否进口',
            field: 'importFlag',
            component: 'Render',
            colSpan: open?.record?.supplyWay && open?.record?.supplyWay == 1 ? (!open?.record.importFlag ? 2 : 1) : 0,
            slotRender: (text: any = 0) => {
              return <span style={{ marginLeft: 8 }}>{text == 0 ? '否' : '是'}</span>;
            },
          },
          {
            label: '进口专业人员论证意见',
            field: 'needImportURL',
            placeholder: '请上传进口专业人员论证意见',
            component: 'Render',
            colSpan: 1,
            ishidden: open?.record?.supplyWay && open?.record?.supplyWay == 1 && open?.record?.importFlag == 1 ? false : true,
            // required: true,
            slotRender: () => {
              return (
                <span style={{ marginLeft: 8 }}>
                  {renderFileFunc({
                    record: open?.record || {},
                    fileName: 'needImportURL',
                    downloadAddress: '/purchaseApplyController/downloadFile',
                    returnStr: '/',
                  })}
                </span>
              );
            },
          },
          {
            label: '是否单一来源',
            field: 'singleFlag',
            component: 'Render',
            colSpan: open?.record?.supplyWay && open?.record?.supplyWay == 1 ? (!open?.record.singleFlag ? 2 : 1) : 0,
            slotRender: (text: any = 0) => {
              return <span style={{ marginLeft: 8 }}>{text == 0 ? '否' : '是'}</span>;
            },
          },
          {
            label: '单一来源论证意见',
            field: 'needSingleURL',
            placeholder: '请上传单一来源论证意见',
            component: 'Render',
            colSpan: 1,
            ishidden: open?.record?.supplyWay && open?.record?.supplyWay == 1 && open?.record?.singleFlag == 1 ? false : true,
            // required: true,
            slotRender: () => {
              return (
                <span style={{ marginLeft: 8 }}>
                  {renderFileFunc({
                    record: open?.record || {},
                    fileName: 'needSingleURL',
                    downloadAddress: '/purchaseApplyController/downloadFile',
                    returnStr: '/',
                  })}
                </span>
              );
            },
          },
          {
            label: '相关附件',
            field: 'relatedUrl',
            placeholder: '请上传相关附件',
            component: 'Render',
            colSpan: 2,
            slotRender: () => {
              return (
                <span style={{ marginLeft: 8 }}>
                  {renderFileFunc({
                    record: open?.record || {},
                    fileName: 'relatedUrl',
                    downloadAddress: '/purchaseApplyController/downloadFile',
                    returnStr: '/',
                  })}
                </span>
              );
            },
          },
          {
            label: '需求论证意见',
            field: 'needProofURL',
            placeholder: '请上传需求论证意见',
            component: 'Render',
            colSpan:
              open?.record?.supplyWay == 1 && open?.record?.expectSum && Number(open?.record?.expectSum) >= 500000
                ? Number(open?.record?.expectSum) >= 1000000
                  ? 1
                  : 2
                : 0,
            // required: true,
            slotRender: () => {
              return (
                <span style={{ marginLeft: 8 }}>
                  {renderFileFunc({
                    record: open?.record || {},
                    fileName: 'needProofURL',
                    downloadAddress: '/purchaseApplyController/downloadFile',
                    returnStr: '/',
                  })}
                </span>
              );
            },
          },
          {
            label: '是否通过主任办公室会议',
            field: 'directorMeetingFlag',
            placeholder: '请上传是否通过主任办公室会议',
            component: 'Render',
            colSpan: open?.record?.supplyWay == 1 && open?.record?.expectSum && Number(open?.record?.expectSum) >= 1000000 ? 1 : 0,
            // required: true,
            slotRender: (text: any = 0) => {
              return <span style={{ marginLeft: 8 }}>{text == 0 ? '否' : '是'}</span>;
            },
          },
        ],
      },
    ],
  });

  /**暴露给父组件的实例值 */
  useImperativeHandle(ref, () => ({ validateFields }));

  /**监听采购申请详情，回显数据*/
  useEffect(() => {
    if (Object.keys(applyInfo).length) {
      setIsShowObj({
        isShowUpload: applyInfo?.supplyWay || 0, // 标的来源
        isShowOther: applyInfo?.purchContent || 0, // 是否展示其他
        isShowCommon: applyInfo?.commonFlag || 0, // 共性
        isShowPlatform: applyInfo?.platformFlag || 0, // 平台
        isShowCategory: applyInfo?.purchCategory || 0, // 采购类别
        isShowConsign: applyInfo?.consignFlag || 0, // 会签
        isShowMeeting: applyInfo?.meetingFlag || 0, // 上会
      });
      // setIsShowUpload(applyInfo?.supplyWay);
      setFieldsValue({ ...applyInfo, expectSum: formatDecimal(applyInfo?.expectSum) });
      const { packs = [] } = applyInfo;
      let clone_packs = [...packs];
      setPackList(clone_packs);
    }
  }, [applyInfo]);

  /**改变显示抽屉状态*/
  const onSetOpen = (res) => {
    methods?.setFieldsValue(res?.record);
    setOpen(res);
  };

  const dataMemo = useMemo(() => {
    if (open?.isShow && open?.record?.SourceData) {
      let data = handleOneObjectData(open?.record?.SourceData);
      return data;
    } else {
      return [];
    }
  }, [open?.isShow, open?.record]);

  return (
    <>
      <DescriptionsType config={config} />
      <UpdatePackList packList={packList} onSetOpen={onSetOpen} />
      <Drawer
        title="标包信息"
        placement="right"
        closable={false}
        onClose={() => setOpen({})}
        open={open?.isShow}
        getContainer={false}
        style={{ position: 'absolute' }}
        width={document.body?.clientWidth * 0.5}
        bodyStyle={{ padding: 0, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}
        className={'packInfoDrawer'}
      >
        <ScrollBarLayout style={{ padding: '10px', display: 'flex', flexDirection: 'column' }}>
          <DescriptionsType config={configs} />
          <div className={'apply-update-title-divClassName'}>二、标包物料</div>
          <div className={`list-table`}>
            <Table
              bordered
              size={'small'}
              rowKey={'materialID'}
              pagination={false}
              rowClassName={setTableRowClassName}
              scroll={{ x: 1000, y: 1000 }}
              dataSource={dataMemo}
              rowSelection={undefined}
              columns={getPackTableColumns({
                applyInfo,
                finallyType: 'view',
                changeTargetInfo: () => {},
                onRemove: () => {},
              })}
            />
          </div>
        </ScrollBarLayout>
      </Drawer>
    </>
  );
});

export default UpdateStepsApply;
